// Package serverapp 服务器顶层接口实现
// main函数里申请和使用
package serverapp

import (
	"context"
	"wanyu/server/engine/wpcfg"
	"wanyu/server/engine/wperror"
	"wanyu/server/engine/wplog"

	cst "wanyu/server/engine/globaldef/consts"
	"wanyu/server/engine/utils"
	"wanyu/server/engine/version"

	"github.com/micro/go-micro/config"
)

//SeverApp 服务器App顶层接口
type SeverApp struct {
	context context.Context
	ws      WindService
}

//Init 初始化
func (app *SeverApp) Init(ws WindService) error {
	//wplog.Infof("ServerApp Init ...")

	if ws == nil {
		return wperror.NewError(wperror.ErrorInit, "windService doesn't set!")
	}
	app.ws = ws
	app.context = context.Background()

	// 读取配置
	path := utils.GetCurDir()
	cfgFile := path + "/" + ws.Name() + ".json"
	var err error
	var cfg config.Config
	if cfg, err = wpcfg.SyncLoadFile(cst.ConfigServer, cfgFile); err != nil {
		return err
	}
	// 得到log配置数据
	outputFile :=  cfg.Get("logcfg", "outputFile").String("output.log")
	cfgJSON := cfg.Get("logcfg", "cfgParamm").Bytes()

	// 日志初始化
	if err = wplog.InitLogger(
		wplog.WithSource(ws.Name()),
		wplog.WithOutput(outputFile),
		wplog.WithCfg(cfgJSON)); err != nil {
		return err
	}

	wplog.Info("sevice version:", version.SERVICE_VERSION)
	wplog.Info("git version:", version.GIT_VERSION)
	wplog.Info("build date:", version.BUILD_DATE)
	wplog.Info("build ip:", version.BUILD_IP)

	if err = app.ws.Init(app.context); err != nil {
		return err
	}

	wplog.Infof("ServerApp Init successful.")
	return nil
}

//Run 运行服务器
func (app *SeverApp) Run() error {
	app.ws.Run()
	return nil
}
